package cn.tedu.web.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.CaptchaUtil;
import cn.tedu.web.service.IAdministratorService;
import cn.tedu.web.service.IUserService;
import cn.tedu.web.service.IWalletService;
import cn.tedu.web.utils.ResponseUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@Api(value = "User", tags = { "User" }, description = "用户相关")
@RequestMapping("/auth")
public class SessionController {
	@Autowired
	private IAdministratorService administratorService;
	@Autowired
	private IUserService userService;
	@Autowired
	public IWalletService walletService;

	@ResponseBody
	@ApiOperation(value = "管理员登录")
	@RequestMapping("AdminLogin")
	public ResponseEntity<Object> Login(@RequestBody JSONObject param, HttpSession session) {
		// System.out.println(param.toJSONString());
		Long id = administratorService.login(param.getString("username"), param.getString("password"));
		// 将 ID 存储到 Session 中。
		if (id != null && id > 0L) {
			session.setAttribute("ID", id);
			return new ResponseEntity<>(id, HttpStatus.OK);
		}
		return new ResponseEntity<>("密码错误", HttpStatus.INTERNAL_SERVER_ERROR);
	}

	/**
	 * 登录
	 * 
	 * @param email    邮箱
	 * @param password 密码
	 * @param code     验证码
	 */
	@ApiOperation(value = "用户登录")
	@PostMapping("login")
	public ResponseUtil<Object> login(@RequestBody JSONObject param, HttpSession session) {
		String email = param.getString("email");
		String password = param.getString("password");
		String code = param.getString("code");
		if (StringUtils.isAnyBlank(email, password)) {
			// 如果邮箱或密码为空，则认为是参数错误
			return new ResponseUtil<>(-1, "ERROR_ARGUMENTS", null);
		}
		if (StringUtils.isEmpty(code)) {
			// 如果没有验证码，则提示错误
			return new ResponseUtil<>(-1, "EMPTY_CODE", null);
		}
		// 验证验证码
		Object captcha = session.getAttribute("CAPTCHA");
		if (captcha == null || !captcha.toString().equals(code)) {
			// 如果验证码错误，则提示错误
			return new ResponseUtil<>(-1, "ERROR_CODE", null);
		}
		// 返回 NULL，说明账号和密码不匹配，返回负数，说明账号不存在，返回正数，说明账号和密码匹配
		Integer id = userService.findUserByEmailAndPassword(email, password);
		if (id == null) {
			return new ResponseUtil<>(-1, "ERROR_PASSWORD", null);
		} else if (id < 0) {
			return new ResponseUtil<>(-1, "ERROR_ACCOUNT", null);
		}
		// id 为正数，说明账号允许登录，则将 id 存储到 session 中，以便于后续使用。
		session.setAttribute("UID", id);
		return new ResponseUtil<>(1, "OK", id);
	}

	@ApiOperation(value = "验证码")
	@GetMapping("captcha")
	public void captcha(HttpServletResponse response, HttpSession session) throws IOException {
		// 创建一个验证码
		AbstractCaptcha captcha = CaptchaUtil.createLineCaptcha(300, 80);
		// // 获取随机的验证码字符
		String code = captcha.getCode();
		// 将验证码的字符存储到会话中
		session.setAttribute("CAPTCHA", code);
		System.out.println(code);
		// 将验证码图片输出到浏览器
		captcha.write(response.getOutputStream());
	}

	/**
	 * 注册
	 */
	@ApiOperation(value = "用户注册")
	@RequestMapping("register")
	public String register(@RequestBody JSONObject param) {
		String email = param.getString("email");
		String password = param.getString("password");
		String nickname = param.getString("username");
		String msg = userService.register(email, password, nickname);
		if (msg == "OK") {
			Integer uid = userService.findUserByEmailAndPassword(email, password);
			// 初始化钱包密码
			walletService.initPaymentPassword(uid, password);
		}
		return msg;
	}

	// 激活
	@ApiOperation(value = "用户激活")
	@RequestMapping("active")
	public String active(Integer id) throws IOException {
		String projectPath = System.getProperty("user.dir");
		System.out.println(projectPath + "/template/generator/mybatis/controller.java");// 生成文件的输出目录
		// String status = userService.active(id);
		return userService.active(id);
	}

	// 退出登录
	@ResponseBody
	@ApiOperation(value = "退出登录")
	@RequestMapping("logout")
	public ResponseEntity<Object> logOut(HttpSession session) {
		// System.out.println(param.toJSONString());
		// 将 ID 设为null后存储到 Session 中。
		session.setAttribute("ID", null);
		return new ResponseEntity<>("logout", HttpStatus.OK);
	}

}